package com.yskj.mwk.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.Page;
import com.yskj.mwk.bean.*;
import com.yskj.mwk.dao.UserMapper;
import com.yskj.mwk.service.UserService;
import com.yskj.mwk.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private final WxUtils wxUtils;
    private final JiTuUtil jiTuUtil;

    @Autowired
    private UserMapper userMapper;



    @Autowired
    public UserServiceImpl(WxUtils wxUtils,JiTuUtil jiTuUtil) {
        this.wxUtils = wxUtils;
        this.jiTuUtil = jiTuUtil;
    }

    @Override
    public List<User> getUsers() {
        return userMapper.getUsers();
    }

    /**
     * 获取手机号并与openid相关联
     * */
    @Override
    public User getUserTellByCode( String code,String openid) {
        String accessToken=wxUtils.getAccessToken();
        try {
            String json="{\"code\":\""+code+"\"}";
            String result=HttpClientUtils.sendPostRequest("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken,json);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(result);
            JsonNode errcode = rootNode.get("errcode");
            int ecode=errcode.asInt();
            if(ecode==0){
                JsonNode phone_info = rootNode.get("phone_info");
                JsonNode purePhoneNumber = phone_info.get("purePhoneNumber");
                String tell=purePhoneNumber.asText();
                //判断此手机号是否注册过，注册过返回用户信息，没注册则注册返回用户信息
                User user=userMapper.getUsersByTell(tell);
                if (user==null){
                    UUID uuid = UUID.randomUUID();
                    user=new User();
                    user.setOpenid(openid);
                    user.setTell(tell);
                    user.setUuid(uuid.toString());
                    user.setName("微信用户"+(System.currentTimeMillis()/1000));
                    int resultNum=userMapper.insertUser(user);
                    if (resultNum>0){
                        return user;
                    }else{
                        return null;
                    }
                }else{
                    userMapper.updateOpenidByTell(openid,tell);
                    return user;
                }
            }else{
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 获取openid
     * */
    @Override
    public String getWxOpenId(String code) {
        return wxUtils.getOpenid(code);
    }

    /**
     * 根据openid获取用户的uuid
     * */
    @Override
    public String getUserUuid(String openid) {
        Map<String,Object> map=userMapper.getUserUuid(openid);
        if (map==null){
            return null;
        }else{
            int isBindTell=(Integer)map.get("isBindTell");
            if (isBindTell==0){
                return null;
            }else{
                return map.get("uuid").toString();
            }
        }
    }

    /**
     * 获取用户详情
     * */
    @Override
    public User getUserDescByUuid(String uuid) {
        return userMapper.getUserDescByUuid(uuid);
    }

    /**
     * 修改用户的昵称或头像
     * */
    @Override
    public int updateUserInfo(String uuid, String headUrl, String name) {

        return userMapper.updateUserInfo(name,headUrl,uuid);
    }

    /**
     * 修改地址
     * */
    @Override
    public int updateAddress(Address address) {

        return userMapper.updateAddressById(address);
    }

    /**
     * 新增地址
     * */
    @Override
    public int addAddress(Address address) {
        return userMapper.insertAddress(address);
    }

    /**
     * 先设置所有地址为不默认
     * */
    @Override
    public int updateNoAddressDefault(String uuid) {
        return userMapper.updateAddressNoDefault(uuid);
    }

    /**
     * 设置某地址为默认地址
     * */
    @Override
    public int updateAddressDefault(int id) {
        return userMapper.updateAddressDefault(id);
    }

    /**
     * 删除地址
     * */
    @Override
    public int deleteAddressById(int id) {
        return userMapper.deleteAddressById(id);
    }

    /**
     * 获取某用户的地址列表
     * */
    @Override
    public List<Address> getAllAddressByUuid(String uuid) {
        return userMapper.getAllAddressByUuid(uuid);
    }

    /**
     * 地址详情
     * */
    @Override
    public Address getAddressDesc(int id) {
        return userMapper.getAddressDesc(id);
    }

    /**
     * 获取一级分类
     * */
    @Override
    public List<Sort> getOneLevelSort() {
        return userMapper.getOneLevelSort();
    }

    /**
     * 获取某一级分类其下的二级分类
     * */
    @Override
    public List<Sort> getSecondLevelSort(int parentId) {
        return userMapper.getSecondLevelSort(parentId);
    }

    /**
     * 搜索名字符合的商品
     * */
    @Override
    public PageInfo<Goods> getGoodsBySearchName(String name, int pageNum, int pageSize) {
        Page<Goods> goodsPage = userMapper.selectGoodsByNamePageList(name, pageNum, pageSize); // 确保Mapper接口返回的是Page<User>类型
        return new PageInfo<>(goodsPage);
    }

    /**
     * 新品--商品列表
     * */
    @Override
    public PageInfo<Goods> getIndexNewGoods(int pageNum, int pageSize,int type) {
        Page<Goods> goodsPage =null;
        if (type==1){
            goodsPage=userMapper.getIndexNewGoods1(pageNum, pageSize);
        }else if (type==2){
            goodsPage=userMapper.getIndexNewGoods2(pageNum, pageSize);
        }else{
            goodsPage=userMapper.getIndexNewGoods3(pageNum, pageSize);
        }
        return new PageInfo<>(goodsPage);
    }

    /**
     * 热门推荐-商品列表
     * */
    @Override
    public PageInfo<Goods> getIndexPopularGoods(int pageNum, int pageSize) {
        Page<Goods> goodsPage =userMapper.getIndexPopularGoods(pageNum, pageSize);
        return new PageInfo<>(goodsPage);
    }

    /**
     * 二级分类下商品列表
     * sort2Id传0则获取一级分类下全部商品
     * */
    @Override
    public PageInfo<Goods> getGoodsBySortId(int pageNum, int pageSize,int sort1Id, int sort2Id) {
        Page<Goods> goodsPage;
        if (sort2Id==0){
            goodsPage = userMapper.getALLGoodsBySortId1(pageNum, pageSize, sort1Id);
        }else{
            goodsPage = userMapper.getALLGoodsBySortId2(pageNum, pageSize, sort2Id);
        }
        return new PageInfo<>(goodsPage);
    }

    /**
     * 获取我的收藏，按照收藏时间降序
     * */
    @Override
    public PageInfo<CollectGoods> getMyCollectedGoods(int pageNum, int pageSize, String uuid) {
        Page<CollectGoods> goodsPage =userMapper.getMyCollectedGoods(pageNum, pageSize,uuid);
        return new PageInfo<>(goodsPage);
    }

    /**
     * 取消收藏
     * */
    @Override
    public int cancelCollectionById(int id,String uuid) {
        return userMapper.cancelCollectionById(id,uuid);
    }

    /**
     * 新增收藏
     * */
    @Override
    public int addCollectionById(int id,String uuid) {
        Goods goods=userMapper.getGoodsSpu(id);
        //判断商品是否下架或者删除
        int publishStatus=goods.getPublishStatus();
        int isDelete=goods.getIsDelete();
        if (publishStatus==1&&isDelete==0){
            int spuId=goods.getSpuId();
            String collectTime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
            BigDecimal collectPrice=goods.getPrice();
            return userMapper.addCollectionById(uuid,spuId,collectTime,collectPrice);
        }else{
            return 0;
        }

    }

    /**
     * 获取商品详情
     * */
    @Override
    public GoodsDesc getGoodsDescById(int id) throws JsonProcessingException {
        GoodsDesc goodsDesc=new GoodsDesc();
        //先获取spu表信息
        Goods goods=userMapper.getGoodsSpu(id);
        goodsDesc.setGoods(goods);
        //获取sku属性信息 json格式字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> linkedHashMap = objectMapper.readValue(userMapper.getGoodsSpuGuige(id), LinkedHashMap.class);
            goodsDesc.setSpec_template(linkedHashMap);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
        //goodsDesc.setSpec_template();
        //获取商品详情页的轮播图
        goodsDesc.setCommonPicList(userMapper.getGoodsPicsByType(id,1));
        //获取商品详情页下方详情图
        goodsDesc.setDetailPicList(userMapper.getGoodsPicsByType(id,2));
        //获取进入编辑diy页的提示图
        goodsDesc.setTipPicList(userMapper.getGoodsTipPic(id));
        return goodsDesc;
    }

    /**
     * 判断用户是否收藏此商品
     * */
    @Override
    public int checkGoodsIsCollect(int id, String uuid) {
        return userMapper.checkGoodsIsCollect(id,uuid);
    }

    /**
     * 根据选择的规格获取商品的缩略图和价格
     * 名称和描述
     * */
    @Override
    public GoodsSku getGoodsSkuByIndexStr(int id, String index) {

        return userMapper.getGoodsSkuByIndexStr(id,index);
    }

    /**
     * 测试用
     * 批量新增sku
     * */
    @Override
    public int batchAddSkuTest(int id) {
        Goods goods=userMapper.getGoodsSpu(id);
        int sort1Id=goods.getSort1Id();
        int sort2Id=goods.getSort2Id();
        String spec=userMapper.getGoodsSkuSpecById(id);
        GenerateGoodsSkuUtil generateGoodsSkuUtil=new GenerateGoodsSkuUtil();
        List<GoodsSpec> goodsSpecList=generateGoodsSkuUtil.generate(spec);
        String createTime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        for (GoodsSpec goodsSpec:goodsSpecList) {
            System.out.println(goodsSpec);
            String own_spec=goodsSpec.getOwn_spec();
            String indexes=goodsSpec.getIndexes();

            AddSkuBean addSkuBean=new AddSkuBean();
            addSkuBean.setSpuId(id);
            addSkuBean.setSort1Id(sort1Id);
            addSkuBean.setSort2Id(sort2Id);
            addSkuBean.setIndexes(indexes);
            addSkuBean.setOwn_spec(own_spec);
            addSkuBean.setCreateTime(createTime);
            userMapper.addSkuSpec(addSkuBean);
            userMapper.addSkuStock(addSkuBean.getSkuId());
        }
        return 1;
    }

    /**
     * 加购商品到购物车
     * */
    @Override
    public int addGoodsInCar(int skuId, int spuId, String uuid, int num) {
        Car car=new Car();
        car.setSpuId(spuId);
        car.setSkuId(skuId);
        car.setUuid(uuid);
        car.setNum(num);
        car.setCreateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
        car.setCreateTimestamp(System.currentTimeMillis());
        GoodsSku goodsSku=userMapper.getGoodsSkuBySkuId(skuId);
        car.setIndexes(goodsSku.getIndexes());
        String specStr=goodsSku.getOwn_spec();
        GenerateGoodsSkuUtil generateGoodsSkuUtil=new GenerateGoodsSkuUtil();
        car.setOwn_spec(generateGoodsSkuUtil.getSpecStr(specStr));
        Goods goods=userMapper.getGoodsSpu(spuId);
        car.setMinNum(goods.getMinNum());
        car.setSupplierId(goods.getSupplierId());
        int res=userMapper.addGoodsInCar(car);
        if (res>=1){
            return car.getId();
        }else{
            return 0;
        }
    }

    /**
     * 从购物车删除商品
     * */
    @Override
    public int deleteGoodsInCarById(int id) {
        return userMapper.deleteGoodsInCarById(id);
    }

    /**
     * 获取购物车列表
     * */
    @Override
    public PageInfo<Car> getMyCarGoods(int pageNum, int pageSize, String uuid) {
        Page<Car> carPage =userMapper.getMyCarGoods(pageNum, pageSize,uuid);
        return new PageInfo<>(carPage);
    }

    /**
     * 修改购物车的商品数量
     * */
    @Override
    public int updateGoodsNumInCar(int id, int num) {
        return userMapper.updateGoodsNumInCar(id,num);
    }

    /**
     * 修改购物车的商品的规格
     * */
    @Override
    public Map<String, Object> updateGoodsGuigeInCar(int id, String index,int spuId) {
        GoodsSku goodsSku=userMapper.getGoodsSkuByIndexStr(spuId,index);
        int skuId=goodsSku.getSkuId();
        int enable=goodsSku.getEnable();
        String specStr=goodsSku.getOwn_spec();
        GenerateGoodsSkuUtil generateGoodsSkuUtil=new GenerateGoodsSkuUtil();
        int result=userMapper.updateGoodsGuigeInCar(id,skuId,index,generateGoodsSkuUtil.getSpecStr(specStr));
        if (result>0){
            Map<String, Object> map=new HashMap<>();
            map.put("specStr",generateGoodsSkuUtil.getSpecStr(specStr));
            map.put("enable",enable);
            return map;
        }else{
            return null;
        }
    }

    /**
     * 获取商品的规格
     * */
    @Override
    public Map<String, Object> getSpecJsonBySpuId(int spuId) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(userMapper.getGoodsSpuGuige(spuId), LinkedHashMap.class);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 购物车下单
     * */
    @Override
    public SystemOrderDesc addOrder(String ids, String uuid) {
        SystemOrderDesc sOrderDesc=new SystemOrderDesc();
        //先查看用户有没有默认地址，有则预设，没有则为空
        Address address=userMapper.getDefaultAddressDescByUuid(uuid);
        String receiveName="";
        String receiveTell="";
        String receiveAddress="";
        int addressId=0;
        if (address!=null){
            addressId=address.getId();
            receiveName=address.getLxrname();
            receiveTell=address.getLxrtell();
            receiveAddress=address.getProvince()+address.getCity()+address.getDistrict()+address.getLxraddress();
        }

        //创建用于支付的订单（系统订单）
        OrderNumberGenerator generator = new OrderNumberGenerator();
        String systemId=generator.generateOrderNumber();
        String createTime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        String yujiTime = DateUtil.format(
                DateUtil.offsetDay(DateUtil.date(), 7),
                "yyyy-MM-dd HH:mm:ss"
        );
        SystemOrder systemOrder=new SystemOrder();
        systemOrder.setSystemId(systemId);
        systemOrder.setUuid(uuid);
        systemOrder.setCreateTime(createTime);
        systemOrder.setPayStatus(0);
        systemOrder.setAddressId(addressId);
        systemOrder.setReceiveName(receiveName);
        systemOrder.setReceiveTell(receiveTell);
        systemOrder.setReceiveAddress(receiveAddress);
        int res1=userMapper.addSystemOrder(systemOrder);
        if (res1>0){
            //把购物车商品按照供应商分类，判断需要几个订单包裹
            List<Integer> idsList = Arrays.stream(ids.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            List<SupplierIdsDTO> supplierIdsList=userMapper.getSupplierIdByIds(idsList,uuid);
            //System.out.println(supplierIdsList);
            List<OrderBean> orderBeanList=new ArrayList<>();
            BigDecimal sTotalPrice=new BigDecimal(0);
            for (SupplierIdsDTO supplierIds : supplierIdsList) {
                OrderBean orderBean=new OrderBean();

                int supplierId = supplierIds.getSupplierId();
                String carIds = supplierIds.getIds();
                //生成用户订单
                String orderId=generator.generateOrderNumber();
                String[] carIdsArray = carIds.split(",");
                BigDecimal oTotalPrice=new BigDecimal(0);
                List<OrderDesc> orderDescList=new ArrayList<>();
                for (String carid : carIdsArray) {
                    int carId=Integer.parseInt(carid);
                    Car car=userMapper.getMyCarGoodsDesc(carId);
                    int skuId=car.getSkuId();
                    int spuId=car.getSpuId();
                    int enable=car.getEnable();
                    int publishStatus=car.getPublishStatus();
                    int buyNum=car.getNum();
                    int stock=userMapper.getStock(skuId);
                    if(enable==1&&publishStatus==1&&buyNum>0&&stock>=buyNum){
                        //查看此商品是否能下单，库存
                        OrderDesc oDesc=new OrderDesc();
                        oDesc.setOrderId(orderId);
                        BigDecimal unitPrice=car.getSalesPrice();//单价
                        oDesc.setUnitPrice(unitPrice);
                        oDesc.setNum(buyNum);
                        BigDecimal bNum = new BigDecimal(buyNum);
                        oDesc.setSubtotal(unitPrice.multiply(bNum));
                        oDesc.setSkuId(skuId);
                        oDesc.setSpuId(spuId);
                        oDesc.setCarId(carId);
                        oDesc.setOrderTime(createTime);
                        oDesc.setSupplierId(supplierId);
                        oDesc.setGoodsName(car.getSpuName());
                        oDesc.setGoodsSpec(car.getOwn_spec());
                        oDesc.setGoodsPic(car.getSkuPic());

                        userMapper.addOrderDesc(oDesc);
                        userMapper.updateEditImageOrderId(orderId,oDesc.getOid(),carid);
                        oTotalPrice=oTotalPrice.add(unitPrice.multiply(bNum));
                        orderDescList.add(oDesc);
                    }else{
                        continue;
                    }
                }
                //建立用户（租户）订单表
                Order order=new Order();
                order.setOrderId(orderId);
                order.setCreateTime(createTime);
                order.setReceiveName(receiveName);
                order.setReceiveTell(receiveTell);
                order.setReceiveAddress(receiveAddress);
                order.setAddressId(addressId);
                order.setShippingFee(new BigDecimal(0));
                order.setUuid(uuid);
                order.setSystemId(systemId);
                order.setSupplierId(supplierId);
                order.setTotalPrice(oTotalPrice);
                order.setYujifahuo(yujiTime);
                userMapper.addOrder(order);
                orderBean.setOrder(order);
                orderBean.setOrderDescs(orderDescList);
                orderBeanList.add(orderBean);
                sTotalPrice=sTotalPrice.add(oTotalPrice);
            }
            sOrderDesc.setSystemOrder(systemOrder);
            sOrderDesc.setOrderBeanList(orderBeanList);
            //添加总价到系统订单中
            userMapper.updateSystemOrderPrice(sTotalPrice,systemId);
            systemOrder.setTotalPrice(sTotalPrice);
        }

        return sOrderDesc;
    }

    @Override
    public PageInfo<MyOrder> getMyOrders(String uuid, int orderStatus, int pageNum, int pageSize) {
        if (orderStatus==0){
            //获取全部有效订单
            Page<MyOrder> ordersPage=userMapper.getMyAllOrders(uuid,pageNum,pageSize);
            return new PageInfo<>(ordersPage);
        }else{
            Page<MyOrder> ordersPage=userMapper.getMyOrdersByOrderStatus(uuid,orderStatus,pageNum,pageSize);
            return new PageInfo<>(ordersPage);
        }
    }

    /**
     * 获取售后订单
     * orderStatus=5
     * afterStatus=1or2
     * */
    @Override
    public PageInfo<MyOrder> getMyAfterOrders(String uuid, int pageNum, int pageSize) {
        Page<MyOrder> ordersPage=userMapper.getMyAfterOrders(uuid,pageNum,pageSize);
        return new PageInfo<>(ordersPage);
    }

    @Override
    public OrderBean getMyOrderDescById(String orderId) {
        OrderBean orderBean=new OrderBean();
        orderBean.setOrder(userMapper.getOrderByOrderId(orderId));
        orderBean.setOrderDescs(userMapper.getOrderDescByOrderId(orderId));
        return orderBean;
    }

    @Override
    public int updateOrderStatus(String orderId, int orderStatus,String url) {
        Order order=userMapper.getOrderByOrderId(orderId);
        boolean isMoreThan4Hours=false;
        if (orderStatus==5){
            String addOrderTime=order.getPayTime();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime givenTime = LocalDateTime.parse(addOrderTime, formatter);
            LocalDateTime currentTime = LocalDateTime.now();
            Duration duration = Duration.between(givenTime, currentTime);

            isMoreThan4Hours = duration.toMinutes() > 240;
        }
        if(orderStatus==3){
            //发货需要对接物流那边
            OrderNumberGenerator generator = new OrderNumberGenerator();
            String wlOrderId=generator.generateOrderNumber();
            int jt_res=jiTuUtil.addOrder(orderId,order.getSupplierId(),wlOrderId);
            if (jt_res==0){
                //调用打印方法
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Order order2=userMapper.getOrderByOrderId(orderId);
                int jt_res2=jiTuUtil.printOrder(orderId,order2.getTrackingNo(),order2.getSupplierId(),url);
                System.out.println("【面单打印状态码】:"+jt_res2);
                if (jt_res2!=1){
                    isMoreThan4Hours=true;
                }
//                else{
//                    WxShippingUtil wxShippingUtil=new WxShippingUtil();
//                    String access_token=wxUtils.getAccessToken();
//                    String transaction_id=order.getTransaction_id();
//                    //判断此支付订单是否是最后一个发货的订单
//                    int num=userMapper.getNoFahuoNum(transaction_id);
//                    String is_all_delivered="";
//                    if (num>1){
//                        is_all_delivered="false";
//                    }else{
//                        is_all_delivered="true";
//                    }
//                    String tracking_no=order2.getTrackingNo();
//                    List<OrderDesc> odescList=userMapper.getOrderDescByOrderId(orderId);
//                    String orderDesc="";
//                    if (!odescList.isEmpty()) {
//                        orderDesc=odescList.stream()
//                                .map(OrderDesc::getGoodsName)    // 提取商品名
//                                .filter(goodsName -> goodsName != null && !goodsName.isEmpty()) // 过滤空值
//                                .collect(Collectors.joining(", "));
//                    }
//                    EnhancedPhoneUtils enhancedPhoneUtils=new EnhancedPhoneUtils();
//                    String receiverTell=enhancedPhoneUtils.enhancedMask(order2.getReceiveTell());
//                    User user=userMapper.getUserDescByUuid(order2.getUuid());
//                    String openid=user.getOpenid();
//                    String res=wxShippingUtil.uploadShipping( access_token, transaction_id, is_all_delivered, tracking_no, orderDesc, receiverTell, openid);
//                    if (!res.equals("ok")){
//                        isMoreThan4Hours=true;
//                    }
//                }
            }else{
                isMoreThan4Hours=true;
            }
        }
        int res=0;
        if (!isMoreThan4Hours){
            System.out.println("【是否修改实际订单状态】:是");
            //如果是修改售后状态的 不同意的
            if(orderStatus==8){
                res=userMapper.updateOrderStatus(orderId,2);
                res=userMapper.updateAfterOrderStatus(orderId,3);
            }else{
                res=userMapper.updateOrderStatus(orderId,orderStatus);
                if (orderStatus==5){
                    //同步修改订单的售后状态
                    res=userMapper.updateAfterOrderStatus(orderId,1);
                }
            }
        }else{
            System.out.println("【是否修改实际订单状态】:否");
            res=2;
        }
        return res;
    }

    @Override
    public SystemOrderDesc addOrderNow(String uuid, int spuId, int skuId, int num) {
        SystemOrderDesc sOrderDesc=new SystemOrderDesc();
        //先查看用户有没有默认地址，有则预设，没有则为空
        Address address=userMapper.getDefaultAddressDescByUuid(uuid);
        String receiveName="";
        String receiveTell="";
        String receiveAddress="";
        int addressId=0;
        if (address!=null){
            addressId=address.getId();
            receiveName=address.getLxrname();
            receiveTell=address.getLxrtell();
            receiveAddress=address.getProvince()+address.getCity()+address.getDistrict()+address.getLxraddress();
        }

        //创建用于支付的订单（系统订单）
        OrderNumberGenerator generator = new OrderNumberGenerator();
        String systemId=generator.generateOrderNumber();
        String createTime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        String yujiTime = DateUtil.format(
                DateUtil.offsetDay(DateUtil.date(), 7),
                "yyyy-MM-dd HH:mm:ss"
        );
        SystemOrder systemOrder=new SystemOrder();
        systemOrder.setSystemId(systemId);
        systemOrder.setUuid(uuid);
        systemOrder.setCreateTime(createTime);
        systemOrder.setPayStatus(0);
        systemOrder.setAddressId(addressId);
        systemOrder.setReceiveName(receiveName);
        systemOrder.setReceiveTell(receiveTell);
        systemOrder.setReceiveAddress(receiveAddress);
        int res1=userMapper.addSystemOrder(systemOrder);
        if (res1>0){
            List<OrderBean> orderBeanList=new ArrayList<>();
            BigDecimal sTotalPrice=new BigDecimal(0);
            OrderBean orderBean=new OrderBean();
            Goods goods=userMapper.getGoodsSpu(spuId);
            GoodsSku gSku=userMapper.getGoodsSkuBySkuId(skuId);
            int supplierId = goods.getSupplierId();
            //生成用户订单
            String orderId=generator.generateOrderNumber();
            BigDecimal oTotalPrice=new BigDecimal(0);
            List<OrderDesc> orderDescList=new ArrayList<>();
            int carId=0;
            int enable=gSku.getEnable();
            int publishStatus=goods.getPublishStatus();
            int stock=userMapper.getStock(skuId);
            if(enable==1&&publishStatus==1&& num >0&&stock>= num){
                //查看此商品是否能下单，库存
                OrderDesc oDesc=new OrderDesc();
                oDesc.setOrderId(orderId);
                BigDecimal unitPrice=gSku.getSalesPrice();//单价
                oDesc.setUnitPrice(unitPrice);
                oDesc.setNum(num);
                BigDecimal bNum = new BigDecimal(num);
                oDesc.setSubtotal(unitPrice.multiply(bNum));
                oDesc.setSkuId(skuId);
                oDesc.setSpuId(spuId);
                oDesc.setCarId(carId);
                oDesc.setOrderTime(createTime);
                oDesc.setSupplierId(supplierId);
                oDesc.setGoodsName(goods.getSpuName());
                oDesc.setGoodsSpec(gSku.getOwn_spec());
                oDesc.setGoodsPic(gSku.getSkuPic());

                userMapper.addOrderDesc(oDesc);
                oTotalPrice=oTotalPrice.add(unitPrice.multiply(bNum));
                orderDescList.add(oDesc);
            }
            //建立用户（租户）订单表
            Order order=new Order();
            order.setOrderId(orderId);
            order.setCreateTime(createTime);
            order.setReceiveName(receiveName);
            order.setReceiveTell(receiveTell);
            order.setReceiveAddress(receiveAddress);
            order.setAddressId(addressId);
            order.setShippingFee(new BigDecimal(0));
            order.setUuid(uuid);
            order.setSystemId(systemId);
            order.setSupplierId(supplierId);
            order.setTotalPrice(oTotalPrice);
            order.setYujifahuo(yujiTime);
            userMapper.addOrder(order);
            orderBean.setOrder(order);
            orderBean.setOrderDescs(orderDescList);
            orderBeanList.add(orderBean);
            sTotalPrice=sTotalPrice.add(oTotalPrice);
            sOrderDesc.setSystemOrder(systemOrder);
            sOrderDesc.setOrderBeanList(orderBeanList);
            //添加总价到系统订单中
            userMapper.updateSystemOrderPrice(sTotalPrice,systemId);
            systemOrder.setTotalPrice(sTotalPrice);
        }
        return sOrderDesc;
    }

    /**
     * 新增意见反馈
     * */
    @Override
    public int addFeedback(String uuid, String question) {
        Feedback feedback=new Feedback();
        feedback.setUuid(uuid);
        feedback.setQuestion(question);
        String createTime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        feedback.setCreateTime(createTime);
        return userMapper.addFeedback(feedback);
    }

    @Override
    public List<LogisticsDetail> queryTrajectory(String trackingNo,int supplierId) {
        String jsonString=jiTuUtil.queryTrajectory(trackingNo,supplierId);
//        String jsonString = "[{\"billCode\":\"UT0000359748995\",\"details\":[{\"billCode\":\"UT0000264445622\",\"desc\":\"【南京雨花台春江新城网点】您的极兔小哥 test1040 已取件。如需联系网点，请拨打 15850664590 特殊时期，您的牵挂，让极兔小哥为您速递！ᕱ ᕱ\",\"scanNetworkArea\":\"江宁区\",\"scanNetworkCity\":\"南京市\",\"scanNetworkContact\":\"15850664590\",\"scanNetworkId\":1772,\"scanNetworkName\":\"南京雨花台春江新城网点\",\"scanNetworkProvince\":\"江苏省\",\"scanNetworkTypeName\":\"南京雨花台春江新城网点\",\"scanTime\":\"2020-07-16 09:26:15\",\"scanType\":\"快件揽收\"},{\"billCode\":\"UT0000264445622\",\"desc\":\"亲，有您的快递！【南京玄武网点】的极兔小哥 test1042 (13123456789) 正带着包裹来见您，如需联系该网点，请拨打 17314954950 今天的极兔小哥，体温正常，口罩戴好，消毒到位，即将为您打call\",\"scanNetworkArea\":\"玄武区\",\"scanNetworkCity\":\"南京市\",\"scanNetworkContact\":\"17314954950\",\"scanNetworkId\":33,\"scanNetworkName\":\"南京玄武网点\",\"scanNetworkProvince\":\"江苏省\",\"scanNetworkTypeName\":\"南京玄武网点\",\"scanTime\":\"2020-07-16 09:26:31\",\"scanType\":\"出仓扫描\"}]}]";
        System.out.println(jsonString);
        List<LogisticsDetail> logisticsDetails = new ArrayList<>();

        // 将 JSON 字符串解析为 JSONArray
        JSONArray jsonArray = JSONArray.parseArray(jsonString);

        // 遍历外层的 JSON 数组
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            // 获取 "details" 数组
            JSONArray detailsArray = jsonObject.getJSONArray("details");

            // 遍历 "details" 数组
            for (int j = 0; j < detailsArray.size(); j++) {
                JSONObject detailObject = detailsArray.getJSONObject(j);

                // 提取需要的字段
                String desc = detailObject.getString("desc");
                String scanTime = detailObject.getString("scanTime");
                String scanType = detailObject.getString("scanType");

                // 创建 LogisticsDetail 对象并添加到列表中
                LogisticsDetail logisticsDetail = new LogisticsDetail();
                logisticsDetail.setDesc(desc);
                logisticsDetail.setScanTime(scanTime);
                logisticsDetail.setScanType(scanType);

                logisticsDetails.add(logisticsDetail);
            }
        }
        logisticsDetails.sort(Comparator.comparing(LogisticsDetail::getScanTimeAsLocalDateTime).reversed());
        return logisticsDetails;
    }

    @Override
    public List<WuliuDesc> queryTrajectory2(String trackingNo) {
        return userMapper.getWuliuDesc(trackingNo);
    }

    /**
     * 修改未支付的订单地址
     * */
    @Override
    public int updateOrderAddress(String orderId, int addressId, int type) {
        Address address=userMapper.getAddressDesc(addressId);
        int result=0;
        if (type==1){
            int res=userMapper.updateSysAddress(address.getLxrname(),address.getLxrtell(),address.getProvince()+address.getCity()+address.getDistrict()+address.getLxraddress(),address.getId(),orderId);
            if (res==1){
                int res2=userMapper.updateSysAddress2(address.getLxrname(),address.getLxrtell(),address.getProvince()+address.getCity()+address.getDistrict()+address.getLxraddress(),address.getId(),orderId);
                if (res2>0){
                    result=1;
                }
            }
        }else{
            result=userMapper.updateSupplierOrderAddress(address.getLxrname(),address.getLxrtell(),address.getProvince()+address.getCity()+address.getDistrict()+address.getLxraddress(),address.getId(),orderId);
        }
        return result;
    }

    @Override
    public int checkOrderStatus(String orderId, int type) {
        return 0;
    }

    @Override
    public int updateSysOrderStatus(String orderId, int type) {
        int result=0;
        if (type==1){
            result=userMapper.updateSystemOrderStatus1(orderId);
        }else{
            result=userMapper.updateSystemOrderStatus2(orderId);
        }
        return result;
    }

    @Override
    public List<TemplateSort> getTempImageSort(int spuId,int type) {
        Goods goods=userMapper.getGoodsSpu(spuId);
        return userMapper.getTempImageSort(goods.getSourceId(),type);
    }

    @Override
    public List<TemplateImage> getTempImageBySortId(int sortId,int spuId,int type) {
        if (sortId==0){
            //获取资源包下全部图片
            Goods goods=userMapper.getGoodsSpu(spuId);
            int sourceId=goods.getSourceId();
            return userMapper.getTempImageBysourceId(sourceId,type);
        }else{
            return userMapper.getTempImageBySortId(sortId);
        }
    }

    @Override
    public int saveEditImage(String orderId, int oid, String editImage1, String editImage2,String num) {
        String[] arr1 = editImage1.split(";");
        String[] arr2= editImage2.split(";");
        String[] arr3= num.split(";");
        int length=arr1.length;
        int res=1;
        for (int i=0;i<length;i++){
            int result=userMapper.saveEditImage(oid,orderId,arr1[i],arr2[i], Integer.parseInt(arr3[i]));
            if (result<1){
                res=0;
            }
        }
        return res;
    }

    @Override
    public int saveEditImage2(int carId, String editImage1, String editImage2,String num) {
        String[] arr1 = editImage1.split(";");
        String[] arr2= editImage2.split(";");
        String[] arr3= num.split(";");
        int length=arr1.length;
        int res=1;
        for (int i=0;i<length;i++){
            int result=userMapper.saveEditImage2(carId,arr1[i],arr2[i], Integer.parseInt(arr3[i]));
            if (result<1){
                res=0;
            }
        }
        return res;
    }


    /**
     * 获取首页营销海报
     * */
    @Override
    public String getIndexMarketingPoster() {
        return userMapper.getIndexMarketingPoster();
    }

    @Override
    public int getSystemOrderPayStatus(String orderId) {
        return userMapper.getPayState1(orderId);
    }

    @Override
    public String getTankuangEditTipImage(int spuId,int imageType) {
        return userMapper.getTankuangEditTipImage(spuId,imageType);
    }


    /**
     * 获取 展示页正反 编辑页正反 模板图
     * 背面默认图
     * */
    @Override
    public TempImage getEditTemplateImage(int spuId) {
        TempImage tempImage=new TempImage();
        String show_z=userMapper.getTankuangEditTipImage(spuId,4);
        String show_f=userMapper.getTankuangEditTipImage(spuId,5);
        String edit_z=userMapper.getTankuangEditTipImage(spuId,6);
        String edit_f=userMapper.getTankuangEditTipImage(spuId,7);
        String template_fm=userMapper.getTankuangEditTipImage(spuId,10);
        tempImage.setEditTemp_fm(edit_f);
        tempImage.setEditTemp_zm(edit_z);
        tempImage.setShowTemp_zm(show_z);
        tempImage.setShowTemp_fm(show_f);
        tempImage.setTemplate_fm(template_fm);
        return tempImage;
    }

    @Override
    public long getOrdertotalPriceByOrderId(String orderId, int payType) {
        double originalValue=0;
        if (payType==1){
            //合单支付
            originalValue=userMapper.getSystemOrderMoney(orderId);
        }else{
            originalValue=userMapper.getOrderMoney(orderId);
        }
        BigDecimal bd = new BigDecimal(Double.toString(originalValue));
        bd = bd.multiply(new BigDecimal(100));
        long integerValue = bd.longValue();
        return integerValue;
    }

    /**
     * 支付完成，修改订单状态
     * 并且把订单录入等待区--4小时之后进入生产
     * */
    @Override
    public void wxPayCallbackUpdateOrderStatus(String orderId, String payType,String transactionId,String out_trade_no) {
        String createTime=DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        if (payType.equals("1")){
            int res=userMapper.updatesysOrderIsPay(orderId,transactionId);
            if (res>0){
                userMapper.updatesplOrderIsPay(orderId,transactionId,createTime,out_trade_no);
            }
        }else{
            userMapper.updatesplOrderIsPayById(orderId,transactionId,createTime,out_trade_no);
        }
        String waitOrderId=userMapper.getOrderWaitId(orderId,Integer.parseInt(payType));
        if (waitOrderId==null|| waitOrderId.isEmpty()){
            userMapper.addOrderWait(orderId,System.currentTimeMillis(),Integer.parseInt(payType));
        }
    }


    /**
     * 判断订单是否支付
     * */
    @Override
    public boolean checkOrderIsPay(String orderId, int payType) {
        int result=0;
        if (payType==1){
            result=userMapper.getPayState1(orderId);
        }else{
            result=userMapper.getPayState2(orderId);
        }
        if (result==1){
            return true;
        }else{
            return false;
        }
    }
}
